<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div>
      <titleList :titleListData="['通用管理','用户管理']" />
      <div style="position: absolute;left:150px;top:10px">
        <el-button
          v-if="isAdmin"
          @click="addUser"
          type="primary"
          icon="Plus"
          size="small"
          style="margin: 15px 0 0 40px"
        >新增用户</el-button>
        <!--<el-button @click="dialogVisible = true" type="primary" plain>添加成员</el-button>-->
      </div>
      <div class="search-input-content">
        <el-input
          v-model.trim="searchName"
          @keyup.enter="filterDataset"
          placeholder="搜索用户名称"
          spellcheck="false"
          :suffix-icon="Search"
        >
        </el-input>
      </div>
    </div>
    <div>
      <el-table
        :header-cell-style="{ background: 'rgb(242,242,242)', color: 'rgb(16,16,16)', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ fontSize: '12px', textAlign: 'center' }"
        :data="tableDate.results"
        :row-class-name="tableClass"
      >
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="备注" prop="memo"></el-table-column>
        <el-table-column label="电子邮件" prop="email"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="创建时间" prop="date_joined"></el-table-column>
        <el-table-column label="操作" width="260px">
          <template #default="scope">
            <el-button v-if="isAdmin" @click="edit(scope.$index,scope.row)" size="small" link style="color: rgb(64,149,249)">修改</el-button>
            <el-button v-if="isAdmin" type="primary" :disabled="!scope.row.is_active || scope.row.username === userInfoName" @click="stopUse(scope.$index)" size="small" link style="color: rgb(64,149,249)">停用</el-button>
            <el-button v-if="isAdmin" type="primary" :disabled="scope.row.is_active"  @click="startUse(scope.$index)" size="small" link style="color: rgb(64,149,249)">启用</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <div class="noData">暂无数据</div>
        </template>
      </el-table>
      <div class="row" style="justify-content:flex-end;" v-if="tableDate.results.length>0">
        <el-pagination
          background layout="prev, pager, next"
          style="margin-top: 20px;"
          :total="tableDate.count"
          :current-page="pageData.page"
          :page-size="10"
          @current-change="changePage"
        />
      </div>
    </div>
    <!--停用用户-->
    <el-dialog v-model="stopUseDialog" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <el-icon style="font-size: 20px; color: rgb(250,173,21)"><WarningFilled /></el-icon>
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">停用提醒</span>
          </div>
        </div>
      </template>
      <div style="margin: 0 0 50px 50px;padding: 0">确定停用该用户嘛?请谨慎操作！</div>
      <div style="display: flex;justify-content: flex-end;margin-right: 10px;margin-bottom: 10px">
        <el-button @click="stopUseDialog = false">放弃停用</el-button>
        <el-button type="primary" @click="emitStop">确认停用</el-button>
      </div>
    </el-dialog>
    <!--启用用户-->
    <el-dialog v-model="startUseDialog" :show-close="false" width="500px" :close-on-click-modal="false">
      <template #header="{}">
        <div style="display: flex;justify-content:space-between;margin-top: 10px">
          <div style="display:flex;">
            <el-icon style="font-size: 20px; color: rgb(250,173,21)"><WarningFilled /></el-icon>
            <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">启用提醒</span>
          </div>
        </div>
      </template>
      <div style="margin: 0 0 50px 50px;padding: 0">确定启用该用户嘛?请谨慎操作！</div>
      <div style="display: flex;justify-content: flex-end;margin-right: 10px;margin-bottom: 10px">
        <el-button @click="startUseDialog = false">放弃启用</el-button>
        <el-button type="primary" @click="emitStart">确认启用</el-button>
      </div>
    </el-dialog>
  </q-page>
</template>
<script setup lang="ts">
import {onMounted, reactive, ref, toRaw, nextTick} from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { userList, isUse } from 'src/api/system';
import { ElMessage } from 'element-plus';
import titleList from 'components/subTitleList.vue';
import boxLoading from 'src/components/boxLoading.vue';
import {modelStore} from "stores/model";
const loading = ref(false)
const router = useRouter()
let isEditOrAdd = ref(false);
const showModelStore = modelStore()
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
const isAdmin = JSON.parse(localStorage.getItem('user') || "{}")['is_admin'];//判断用户是否系统普通用户还是超级管理员
const stopUseDialog = ref(false)
const startUseDialog = ref(false)
const searchName = ref('')
const tableIndex = ref(0);
const pageData = ref({
  page: 1
})
let projectId = router.currentRoute.value.params.project_id;


//列表数据
let tableDate = reactive({
  count: 0,
  next: null,
  previous: null,
  results: []
})
//给列表偶数行添加样式
function tableClass({row,rowIndex }:{row:any,rowIndex:any} ) {
  if (rowIndex % 2 == 1) {
    return "even-row";
  } else {
    return "";
  }
}
//新增用户
const addUser = () => {
  showModelStore.setIsEditOrAdd(true);
  router.push({ name: 'system-addSystemUser', params: { project_id: projectId } });//跳转新增界面
}

//修改用户
const edit = (index:any,row:any) => {
  showModelStore.setIsEditOrAdd(false);
  showModelStore.setSystemRowData(row);
  router.push({ name: 'system-addSystemUser', params: { project_id: projectId } })
}
//停用用户
const stopUse = (index:any) => {
  tableIndex.value = index;
  stopUseDialog.value = true;
}
//确认停用
const emitStop = () => {
  use(false,'确认停用成功！！！',stopUseDialog);
}
//启用用户
const startUse = (index:any) => {
  tableIndex.value = index;
  startUseDialog.value = true;
}
//确认启用
const emitStart = () => {
  use(true,'确认启用成功！！！',startUseDialog);
}
function use(is_active:any,message:any,dialogUse:any){
  let params = reactive({
    'is_active': is_active,
    'user_id': toRaw(tableDate.results[tableIndex.value])['id']
  })
  isUse(params).then((res:any) => {
    ElMessage.success(message);
    dialogUse['value'] = false;
    getUserList();
  }).catch(error => {
    ElMessage.error(`请求失败,提示${error.data}`)
  })
}
onMounted(() => {
  getUserList();
})
function filterDataset() {
  pageData.value.page = 1;
  getUserList()
}
function getUserList () {
  loading.value = true;
  let obj = {}
  if (searchName.value != ''){
    obj = {search: searchName.value,page:pageData.value.page}
    obj=Object.assign(obj)
  } else {
    obj = {page:pageData.value.page}
    obj=Object.assign(obj)
  }

  userList(obj).then((res:any) => {
    res.data.results.forEach((item:any) => {
      if (item.role_name){
        item['role_id'] = switchName(item.role_name);
        item['role_id'] === 1?item.role_name = '超级管理员':item.role_name = '普通用户';
      }
    });
    tableDate = res.data
    loading.value = false
  }).catch(error => {
    ElMessage.error(`请求失败,提示${error.data}`)
  })
}
function switchName(role_name:any){
  switch(role_name) {
    case '超级管理员':
      return 1
    case '项目管理员':
      return 2
    default:
      return 2
  }
}

//分页功能
const changePage = (currentPage: any) => {
  pageData.value.page = currentPage
  let limit = 10;
  let offset = 0;
  currentPage > 1 ? offset = (currentPage-1) * limit : offset = 0;
  getUserList()
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body,.el-dialog__body {
  padding: 10px;
}
.search-input-content {
  position: absolute;
  right: 10px;
  top: 18px;
  cursor: pointer
}
::v-deep .even-row {
  background: rgb(242,242,242);
  color: #000
}
</style>
